<?php

namespace App\Http\Controllers\Web;

use Illuminate\Http\Request;
use App\Models\PolityChoices;
use App\Http\Controllers\Controller;
use App\Http\Requests\PolityChoiceWebRequest;

class PolityController extends Controller
{
    public function choice(Request $request)
    {
        if (session('polity_choice')) {
            $data = PolityChoices::findOrfail(session('polity_choice'));
        } else {
            $data = $this->choiceRandom(PolityChoices::get(), $request->input('num', 10));
        }
        return view('web.polity.choice', ['data' => $data]);
    }

    public function result(PolityChoiceWebRequest $request)
    {
        session()->forget('polity_choice');
        $res = array_diff_assoc($request->answer, $request->right);
        if (!$res) {
            return redirect('/')->with('msg', '恭喜！全部回答正确！');
        } else {
            $data = PolityChoices::findOrFail(array_keys($res));
            $data->map(function ($v) use ($res) {
                $v->error = $res[$v->id];
            });
            return view('web.polity.error', ['data' => $data]);
        }
    }
}
